package Multithreading;

import java.util.Scanner;

public class Demo16 {
    /*讲述内存可见性的问题*/
    static class Counter {
        public int flag = 0;
    }
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            while (counter.flag == 0) {
// do nothing
            }
            System.out.println("循环结束!");
        });
        Thread t2 = new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入一个整数:");
            counter.flag = scanner.nextInt();
        });
        t1.start();
        t2.start();
    }
    // 执行效果
    // 当用户输入非0值时, t1 线程循环不会结束. (这显然是一个 bug)
  /*  static class Counter {
        public volatile int flag = 0;
    }*/
    // 执行效果
    // 当用户输入非0值时, t1 线程循环能够立即结束.
}